package com.ethank.system.Utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.aliyun.ocr_api20210707.Client;
import com.aliyun.ocr_api20210707.models.*;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;
import com.ethank.common.core.domain.AjaxResult;
import com.ethank.system.enums.BillEnum;
import com.ethank.system.service.impl.OcrServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Administrator
 */
public class BillUtil {


    private static final Logger logger = LoggerFactory.getLogger(OcrServiceImpl.class);


    /**
     * 混贴发票识别
     *
     * @param file 文件
     * @return 返回数据
     * @throws Exception 异常
     */
    public AjaxResult HTBill(MultipartFile file, String accessKeyId, String accessKeySecret) throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填，您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 必填，您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        config.endpoint = "ocr-api.cn-hangzhou.aliyuncs.com";
        Client client = new Client(config);


        RecognizeMixedInvoicesRequest recognizeMixedInvoicesRequest = new RecognizeMixedInvoicesRequest();
        RuntimeOptions runtime = new RuntimeOptions();

        try {
            byte[] byteArr = file.getBytes();
            InputStream inputStream = new ByteArrayInputStream(byteArr);
            recognizeMixedInvoicesRequest.setBody(inputStream);
            // 复制代码运行请自行打印 API 的返回值
            RecognizeMixedInvoicesResponse recognizeMixedInvoicesResponse =
                    client.recognizeMixedInvoicesWithOptions(recognizeMixedInvoicesRequest, runtime);
            String data = recognizeMixedInvoicesResponse.getBody().getData();
            JSONObject jo = JSON.parseObject(data);
            JSONArray subMsgs = jo.getJSONArray("subMsgs");
            ArrayList<Map<String, Object>> maps = new ArrayList<Map<String, Object>>();
            System.out.println("所有识别后的数据 -----> {}" + subMsgs);
            // 遍历每一个
            subMsgs.forEach(e -> {
                System.out.println("每一条数据 -----> {}" + e);
                HashMap<String, Object> resultMap = new HashMap<>();
                JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(e));
                JSONObject result1 = jsonObject.getJSONObject("result");
                JSONObject data1 = result1.getJSONObject("data");
                if (jsonObject.get("type") != null && !"".equals(jsonObject.get("type"))) {
                    String tp = jsonObject.get("type").toString();
                    Integer billTypeInteger = BillEnum.getTypeByBillTypeName(tp);
                    if (result1.get("ftype") != null) {
                        billType(billTypeInteger, data1, result1.get("ftype").toString());
                    } else {
                        billType(billTypeInteger, data1, "");
                    }
                }

                // 装载数据
                resultMap.put("ftype", result1.get("ftype"));
                resultMap.put("index", jsonObject.get("index"));
                resultMap.put("op", jsonObject.get("op"));
                resultMap.put("type", jsonObject.get("type"));
                resultMap.put("data", data1);
                maps.add(resultMap);
                System.out.println("------------");
            });
            return AjaxResult.success(maps);
        } catch (TeaException error) {
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        return AjaxResult.error();
    }


    /**
     * @Description: 酒店流水识别
     * @Param: [file, accessKeyId, accessKeySecret]
     * @return: com.ethank.common.core.domain.AjaxResult
     * @Author: tf
     * @Date: 2024-02-26
     */
    public AjaxResult hotelConsume(MultipartFile file, String accessKeyId, String accessKeySecret) throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填，您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 必填，您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        config.endpoint = "ocr-api.cn-hangzhou.aliyuncs.com";
        Client client = new Client(config);
        try {
            byte[] byteArr = file.getBytes();
            InputStream inputStream = new ByteArrayInputStream(byteArr);

            RecognizeHotelConsumeRequest recognizeHotelConsumeRequest = new RecognizeHotelConsumeRequest().setBody(inputStream);
            RecognizeHotelConsumeResponse recognizeHotelConsumeResponse =
                    client.recognizeHotelConsume(recognizeHotelConsumeRequest);
            String data = recognizeHotelConsumeResponse.getBody().getData();
            JSONObject jsonObject = JSON.parseObject(data);
            System.out.println("所有识别后的数据 -----> {}" + jsonObject);
            JSONObject resultData = jsonObject.getJSONObject("data");
            return AjaxResult.success(resultData);
        } catch (TeaException error) {
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        return AjaxResult.error();
    }


    /**
     * @Description: 支付详情识别
     * @Param: [file, accessKeyId, accessKeySecret]
     * @return: com.ethank.common.core.domain.AjaxResult
     * @Author: tf
     * @Date: 2024-02-26
     */
    public AjaxResult paymentRecord(MultipartFile file, String accessKeyId, String accessKeySecret) throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填，您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 必填，您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        config.endpoint = "ocr-api.cn-hangzhou.aliyuncs.com";
        Client client = new Client(config);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();

        try {
            byte[] byteArr = file.getBytes();
            InputStream inputStream = new ByteArrayInputStream(byteArr);
            RecognizePaymentRecordRequest recognizePaymentRecordRequest = new RecognizePaymentRecordRequest()
                    .setBody(inputStream);
            RecognizePaymentRecordResponse recognizePaymentRecordResponse =
                    client.recognizePaymentRecordWithOptions(recognizePaymentRecordRequest, runtime);
            String data = recognizePaymentRecordResponse.getBody().getData();
            logger.info("BillUtil=>paymentRecord=>支付详情识别=>{}", data);
            JSONObject jsonObject = JSON.parseObject(data);
            JSONObject resultData = jsonObject.getJSONObject("data");
            return AjaxResult.success(resultData);
        } catch (TeaException error) {
            // 错误 message
            logger.error(error.getMessage());
            // 诊断地址
            logger.error(error.getData().get("Recommend").toString());
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 错误 message
            logger.error(error.getMessage());
            // 诊断地址
            logger.error(error.getData().get("Recommend").toString());
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        return AjaxResult.error();
    }


    public void billType(Integer typeInt, JSONObject dataInfo, String ftype) {
        BillDataUtil billDataUtil = new BillDataUtil();
        switch (typeInt) {
            case 2:
                System.out.println("类型：2");
                break;
            case 3:
                System.out.println("类型：3");
                break;
            case 4:
                billDataUtil.recognizeInvoiceData(dataInfo, ftype);
                break;
            case 5:
                billDataUtil.quotaInvoice(dataInfo, ftype);
                break;
            case 6:
                billDataUtil.airItinerary(dataInfo, ftype);
                break;
            case 7:
                billDataUtil.trainInvoice(dataInfo, ftype);
                break;
            case 8:
                billDataUtil.taxiInvoice(dataInfo, ftype);
                break;
            case 9:
                billDataUtil.rollTicket(dataInfo, ftype);
                break;
            case 10:
                billDataUtil.busShipTicket(dataInfo, ftype);
                break;
            case 11:
                billDataUtil.commonPrintedInvoice(dataInfo, ftype);
                break;
            case 12:
                billDataUtil.rideHailingItinerary(dataInfo, ftype);
                break;
            case 13:
                billDataUtil.tollInvoice(dataInfo, ftype);
                break;
            default:
                System.out.println("系统错误");
        }
    }
}
